package ns3

import (
	"errors"
	"strconv"
	"strings"
)

type TraceRaw struct {
	t     float64
	node  string
	bytes int64
}

type SpaceRaw struct {
	t    float64
	node string
	x    float64
	y    float64
}

func (t TraceRaw) newIAT() (string, IAT) {
	return t.node, IAT{
		T:     t.t,
		Bytes: t.bytes,
	}
}

func (t SpaceRaw) newSpace() Space {
	return Space{
		T:    t.t,
		Node: t.node,
		X:    t.x,
		Y:    t.y,
	}
}

func pareseRange(text string) (*NodeRange, error) {
	nodeRange := new(NodeRange)
	parts := strings.Split(text, "|")
	if len(parts) != 2 {
		return nil, errors.New("{node name}|{range}")
	}

	nodeRange.Node = parts[0]
	nodeRange.Range = parts[1]

	return nodeRange, nil
}

func pareseTopology(text string) (*NodeTopology, error) {
	top := new(NodeTopology)
	parts := strings.Split(text, "|")
	if len(parts) != 2 {
		return nil, errors.New("{node from}|{node to}")
	}

	top.NodeFrom = parts[0]
	top.NodeTo = parts[1]

	return top, nil
}

func parseTrace(text string) (*TraceRaw, error) {
	trace := new(TraceRaw)
	parts := strings.Split(text, "|")
	if len(parts) != 3 {
		return nil, errors.New("{time}|{node name}|{bytes length}")
	}

	t, err := strconv.ParseFloat(parts[0], 64)
	if err != nil {
		return nil, err
	}

	bytesLen, err := strconv.ParseInt(parts[2], 10, 64)
	if err != nil {
		return nil, err
	}

	trace.t = t
	trace.node = parts[1]
	trace.bytes = bytesLen

	return trace, nil
}

func parseSpace(text string) (*SpaceRaw, error) {
	space := new(SpaceRaw)
	parts := strings.Split(text, "|")
	if len(parts) != 4 {
		return nil, errors.New("{time}|{node name}|{x-axis}|{y-axis}")
	}

	t, err := strconv.ParseFloat(parts[0], 64)
	if err != nil {
		return nil, err
	}

	x, err := strconv.ParseFloat(parts[2], 64)
	if err != nil {
		return nil, err
	}

	y, err := strconv.ParseFloat(parts[3], 64)
	if err != nil {
		return nil, err
	}

	space.t = t
	space.node = parts[1]
	space.x = x
	space.y = y

	return space, nil
}
